﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.SignalR;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using BW.WMS.Web.Hubs;
using BW.WMS.WareHouseStatistics;
using BW.WMS.WareHouseManage;

namespace BW.WMS.Web.Services
{
    public class DashboardDataService : ISingletonDependency
    {
        private readonly IHubContext<DashboardHub> _hubContext;
        private Timer _timer;
        private readonly IRepository<StockManagementModel> _stockManagementRepository;

        public DashboardDataService(
            IHubContext<DashboardHub> hubContext,
            IRepository<StockManagementModel> stockManagementRepository)
        {
            _hubContext = hubContext;
            _stockManagementRepository = stockManagementRepository;
        }

        public void StartDataUpdates()
        {
            // 创建定时器，每10秒更新一次数据
            _timer = new Timer(async (state) =>
            {
                try
                {
                    await UpdateDashboardData(state);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Timer callback error: {ex.Message}");
                }
            }, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
        }

        private async Task UpdateDashboardData(object state)
        {
            try
            {
                // 获取所有仪表盘数据
                var overviewStats = await GetCurrentInventoryOverviewAsync();
                var inboundCategoryData = await GetInboundCategoryDataAsync();
                var recentInboundRecords = await GetRecentInboundRecordsAsync();
                var quickNavigation = GetQuickNavigationData();

                // 发送数据给所有客户端
                await _hubContext.Clients.All.SendAsync("OverviewStatsUpdated", overviewStats);
                await _hubContext.Clients.All.SendAsync("InboundCategoryUpdated", inboundCategoryData);
                await _hubContext.Clients.All.SendAsync("RecentInboundRecordsUpdated", recentInboundRecords);
                await _hubContext.Clients.All.SendAsync("QuickNavigationUpdated", quickNavigation);

                // 发送完整的仪表盘数据包
                await _hubContext.Clients.All.SendAsync("DashboardDataUpdated", new
                {
                    OverviewStats = overviewStats,
                    InboundCategory = inboundCategoryData,
                    RecentRecords = recentInboundRecords,
                    QuickNavigation = quickNavigation,
                    Timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error updating dashboard data: {ex.Message}");
            }
        }

        // 获取当前库存概览（基于入库记录计算）
        private async Task<object> GetCurrentInventoryOverviewAsync()
        {
            try
            {
                var queryable = await _stockManagementRepository.GetQueryableAsync();

                // 按货品分组计算当前库存
                var inventoryByGoods = await queryable
                    .Where(s => !s.IsDeleted)
                    .GroupBy(s => new { s.Goodscode, s.Goodstype })
                    .Select(g => new {
                        GoodsCode = g.Key.Goodscode,
                        GoodsType = g.Key.Goodstype,
                        TotalInbound = g.Sum(s => s.Stocknumber ?? 0),
                        TotalAmount = g.Sum(s => s.Stockmoney ?? 0),
                        LastInboundDate = g.Max(s => s.Stocktime)
                    })
                    .ToListAsync();

                // 按类型分组统计
                var inventoryByType = inventoryByGoods
                    .GroupBy(i => i.GoodsType ?? "未分类")
                    .Select(g => new {
                        Type = g.Key,
                        Quantity = g.Sum(i => i.TotalInbound),
                        Amount = g.Sum(i => i.TotalAmount),
                        ItemCount = g.Count()
                    })
                    .OrderByDescending(x => x.Quantity)
                    .ToList();

                return new
                {
                    TotalItems = inventoryByGoods.Count,
                    TotalQuantity = inventoryByGoods.Sum(i => i.TotalInbound),
                    TotalValue = inventoryByGoods.Sum(i => i.TotalAmount),
                    TypeBreakdown = inventoryByType,
                    RecentActivity = inventoryByGoods
                        .OrderByDescending(i => i.LastInboundDate)
                        .Take(5)
                        .ToArray(),
                    Timestamp = DateTime.Now
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取库存概览时出错: {ex.Message}");
                return new
                {
                    TotalItems = 0,
                    TotalQuantity = 0,
                    TotalValue = 0m,
                    TypeBreakdown = new object[0],
                    RecentActivity = new object[0],
                    Timestamp = DateTime.Now
                };
            }
        }

        // 2. 获取入库分类统计数据（饼图）
        private async Task<object> GetInboundCategoryDataAsync()
        {
            try
            {
                var queryable = await _stockManagementRepository.GetQueryableAsync();
                var currentMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);

                var inboundByCategory = await queryable
                    .Where(s => !s.IsDeleted && s.Stocktype != null && s.CreationTime >= currentMonth)
                    .GroupBy(s => s.Stocktype)
                    .Select(g => new {
                        Category = g.Key,
                        Count = g.Count(),
                        TotalQuantity = g.Sum(s => s.Stocknumber ?? 0),
                        TotalAmount = g.Sum(s => s.Stockmoney ?? 0)
                    })
                    .OrderByDescending(x => x.TotalQuantity)
                    .ToListAsync();

                if (!inboundByCategory.Any())
                {
                    return new
                    {
                        Categories = new[] { "生产入库", "调拨入库", "采购入库", "退换入库", "验货入库" },
                        Values = new[] { 0, 0, 0, 0, 0 },
                        Colors = new[] { "#4285f4", "#34a853", "#fbbc04", "#ea4335", "#ff6d01" },
                        Legend = new object[0]
                    };
                }

                var colors = new[] { "#4285f4", "#34a853", "#fbbc04", "#ea4335", "#ff6d01" };
                var legend = inboundByCategory.Select((item, index) => new
                {
                    Name = item.Category,
                    Value = item.TotalQuantity,
                    Color = colors[index % colors.Length],
                    Percentage = inboundByCategory.Sum(x => x.TotalQuantity) > 0
                        ? (double)item.TotalQuantity / inboundByCategory.Sum(x => x.TotalQuantity) * 100
                        : 0
                }).ToArray();

                return new
                {
                    Categories = inboundByCategory.Select(c => c.Category).ToArray(),
                    Values = inboundByCategory.Select(c => c.TotalQuantity).ToArray(),
                    Colors = colors.Take(inboundByCategory.Count).ToArray(),
                    Legend = legend,
                    Timestamp = DateTime.Now
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取入库分类数据时出错: {ex.Message}");
                return new
                {
                    Categories = new string[0],
                    Values = new int[0],
                    Colors = new string[0],
                    Legend = new object[0],
                    Timestamp = DateTime.Now
                };
            }
        }

        // 3. 获取最近入库记录
        private async Task<object> GetRecentInboundRecordsAsync()
        {
            try
            {
                var queryable = await _stockManagementRepository.GetQueryableAsync();

                var recentRecords = await queryable
                    .Where(s => !s.IsDeleted)
                    .OrderByDescending(s => s.CreationTime)
                    .Take(6)
                    .Select(s => new {
                        StockCode = s.Stockcode,
                        StockType = s.Stocktype,
                        GoodsCode = s.Goodscode,
                        Quantity = s.Stocknumber ?? 0,
                        Amount = s.Stockmoney ?? 0,
                        Status = s.Stockstate,
                        CreationTime = s.CreationTime,
                        StatusColor = GetStatusColor(s.Stockstate)
                    })
                    .ToListAsync();

                return new
                {
                    Records = recentRecords.Select(r => new
                    {
                        r.StockCode,
                        r.StockType,
                        r.GoodsCode,
                        Quantity = r.Quantity,
                        Amount = $"¥{r.Amount:F1}K",
                        Status = r.Status ?? "待审核",
                        StatusColor = r.StatusColor,
                        Time = r.CreationTime.ToString("MM/dd HH:mm")
                    }).ToArray(),
                    Timestamp = DateTime.Now,
                    TotalCount = recentRecords.Count
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取最近入库记录时出错: {ex.Message}");
                return new
                {
                    Records = new object[0],
                    Timestamp = DateTime.Now,
                    TotalCount = 0
                };
            }
        }

        // 4. 获取快速导航数据
        private object GetQuickNavigationData()
        {
            return new
            {
                NavigationItems = new[]
                {
                    new
                    {
                        Name = "入库管理",
                        Icon = "warehouse",
                        Color = "#34a853",
                        Url = "/warehouse/inbound",
                        Count = 0 // 可以添加待处理数量
                    },
                    new
                    {
                        Name = "仓库管理",
                        Icon = "storage",
                        Color = "#4285f4",
                        Url = "/warehouse/management",
                        Count = 0
                    },
                    new
                    {
                        Name = "库存查询",
                        Icon = "search",
                        Color = "#fbbc04",
                        Url = "/warehouse/inventory",
                        Count = 0
                    },
                    new
                    {
                        Name = "货位管理",
                        Icon = "location",
                        Color = "#9e9e9e",
                        Url = "/warehouse/location",
                        Count = 0
                    }
                },
                Timestamp = DateTime.Now
            };
        }


        // 辅助方法
        private string GetStatusColor(string status)
        {
            return status switch
            {
                "已审核" => "#34a853",
                "待审核" => "#fbbc04",
                "已拒绝" => "#ea4335",
                _ => "#9e9e9e"
            };
        }

        // 手动触发数据更新的方法
        public async Task TriggerManualUpdate()
        {
            await UpdateDashboardData(null);
        }
    }
}